using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Threading;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing.Printing;


namespace Jonathan
{
	#region StampActions
	public enum StampActions
	{
		EditedBy = 1,
		DateTime = 2,
		Custom = 4
	}
	#endregion

	/// <summary>
	/// A Text Based Note Control.
	/// </summary>
	class ctrlTextNote : UserControl
	{
		#region Controls
		private RichTextBox rtbTemp = new RichTextBox();
		private ctrlNote m_NoteTab;
		private string m_FileName;
		StringReader myReader;
		private System.Windows.Forms.SaveFileDialog sfd1;
		private System.Windows.Forms.FontDialog fontDialog;
		private System.Windows.Forms.ColorDialog colorDialog;
		private RichTextBoxLinks rtbNotes;
        private System.Windows.Forms.PictureBox picSave;
		private System.Windows.Forms.PrintDialog printDialog1;
		private System.Drawing.Printing.PrintDocument printDocument1;
		private System.Windows.Forms.OpenFileDialog openFileDialog;
        private ToolStrip toolStrip1;
        private ToolStripButton tsbSave;
        private ToolStripSeparator toolStripSeparator1;
        private ToolStripButton tsbCut;
        private ToolStripButton tsbCopy;
        private ToolStripButton tsbPaste;
        private ToolStripSeparator toolStripSeparator2;
        private ToolStripButton tsbBold;
        private ToolStripButton tsbItalic;
        private ToolStripButton tsbUnderline;
        private ToolStripButton tsbStrike;
        private ToolStripSeparator toolStripSeparator3;
        private ToolStripButton tsbLeft;
        private ToolStripButton tsbCenter;
        private ToolStripButton tsbRight;
        private ToolStripSeparator toolStripSeparator4;
        private ToolStripButton tsbUndo;
        private ToolStripButton tsbRedo;
        private ToolStripSeparator toolStripSeparator5;
        private ToolStripButton tsbFont;
        private ToolStripButton tsbColor;
        private ToolStripButton tsbStamp;
        private ToolStripButton tsbPrint;

		public ctrlTextNote ()
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();

			// TODO: Add any initialization after the InitializeComponent call

		}

		/// <summary> 
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			base.Dispose( disposing );
		}

		#endregion

		#region Component Designer generated code
		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.sfd1 = new System.Windows.Forms.SaveFileDialog();
			this.fontDialog = new System.Windows.Forms.FontDialog();
			this.colorDialog = new System.Windows.Forms.ColorDialog();
			this.rtbNotes = new RichTextBoxLinks();
			this.picSave = new System.Windows.Forms.PictureBox();
			this.printDialog1 = new System.Windows.Forms.PrintDialog();
			this.printDocument1 = new System.Drawing.Printing.PrintDocument();
			this.toolStrip1 = new System.Windows.Forms.ToolStrip();
			this.tsbSave = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
			this.tsbCut = new System.Windows.Forms.ToolStripButton();
			this.tsbCopy = new System.Windows.Forms.ToolStripButton();
			this.tsbPaste = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
			this.tsbBold = new System.Windows.Forms.ToolStripButton();
			this.tsbItalic = new System.Windows.Forms.ToolStripButton();
			this.tsbUnderline = new System.Windows.Forms.ToolStripButton();
			this.tsbStrike = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
			this.tsbLeft = new System.Windows.Forms.ToolStripButton();
			this.tsbCenter = new System.Windows.Forms.ToolStripButton();
			this.tsbRight = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
			this.tsbUndo = new System.Windows.Forms.ToolStripButton();
			this.tsbRedo = new System.Windows.Forms.ToolStripButton();
			this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
			this.tsbFont = new System.Windows.Forms.ToolStripButton();
			this.tsbColor = new System.Windows.Forms.ToolStripButton();
			this.tsbStamp = new System.Windows.Forms.ToolStripButton();
			this.tsbPrint = new System.Windows.Forms.ToolStripButton();
			this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
			((System.ComponentModel.ISupportInitialize)(this.picSave)).BeginInit();
			this.toolStrip1.SuspendLayout();
			this.SuspendLayout();
			// 
			// sfd1
			// 
			this.sfd1.DefaultExt = "rtf";
			this.sfd1.Filter = "Rich Text Format (*.rtf)|*.rtf";
			this.sfd1.Title = "Save File As...";
			// 
			// rtbNotes
			// 
			this.rtbNotes.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.rtbNotes.BorderStyle = System.Windows.Forms.BorderStyle.None;
			this.rtbNotes.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.rtbNotes.Location = new System.Drawing.Point(16, 40);
			this.rtbNotes.Name = "rtbNotes";
			this.rtbNotes.Size = new System.Drawing.Size(825, 352);
			this.rtbNotes.TabIndex = 3;
			this.rtbNotes.Text = "";
			this.rtbNotes.KeyDown += new System.Windows.Forms.KeyEventHandler(this.rtbNotes_KeyDown);
			this.rtbNotes.SelectionChanged += new System.EventHandler(this.rtbNotes_SelectionChanged);
			this.rtbNotes.MouseDown += new System.Windows.Forms.MouseEventHandler(this.rtbNotes_MouseDown);
			// 
			// picSave
			// 
			this.picSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.picSave.BackColor = System.Drawing.Color.Transparent;
			this.picSave.Image = global::Jonathan.InternalImages.saveHS;
			this.picSave.Location = new System.Drawing.Point(840, 392);
			this.picSave.Name = "picSave";
			this.picSave.Size = new System.Drawing.Size(16, 16);
			this.picSave.TabIndex = 4;
			this.picSave.TabStop = false;
			this.picSave.Visible = false;
			this.picSave.VisibleChanged += new System.EventHandler(this.picSave_VisibleChanged);
			// 
			// printDialog1
			// 
			this.printDialog1.Document = this.printDocument1;
			// 
			// printDocument1
			// 
			this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDocument1_PrintPage);
			// 
			// toolStrip1
			// 
			this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
			this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.tsbSave,
            this.toolStripSeparator1,
            this.tsbCut,
            this.tsbCopy,
            this.tsbPaste,
            this.toolStripSeparator2,
            this.tsbBold,
            this.tsbItalic,
            this.tsbUnderline,
            this.tsbStrike,
            this.toolStripSeparator3,
            this.tsbLeft,
            this.tsbCenter,
            this.tsbRight,
            this.toolStripSeparator4,
            this.tsbUndo,
            this.tsbRedo,
            this.toolStripSeparator5,
            this.tsbFont,
            this.tsbColor,
            this.tsbStamp,
            this.tsbPrint});
			this.toolStrip1.Location = new System.Drawing.Point(0, 0);
			this.toolStrip1.Name = "toolStrip1";
			this.toolStrip1.Size = new System.Drawing.Size(856, 25);
			this.toolStrip1.TabIndex = 5;
			this.toolStrip1.Text = "toolStrip1";
			// 
			// tsbSave
			// 
			this.tsbSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbSave.Image = global::Jonathan.InternalImages.saveHS;
			this.tsbSave.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbSave.Name = "tsbSave";
			this.tsbSave.Size = new System.Drawing.Size(23, 22);
			this.tsbSave.Text = "Save";
			this.tsbSave.Click += new System.EventHandler(this.tsbSave_Click);
			// 
			// toolStripSeparator1
			// 
			this.toolStripSeparator1.Name = "toolStripSeparator1";
			this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
			// 
			// tsbCut
			// 
			this.tsbCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbCut.Image = global::Jonathan.InternalImages.CutHS;
			this.tsbCut.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbCut.Name = "tsbCut";
			this.tsbCut.Size = new System.Drawing.Size(23, 22);
			this.tsbCut.Text = "Cut";
			this.tsbCut.Click += new System.EventHandler(this.tsbCut_Click);
			// 
			// tsbCopy
			// 
			this.tsbCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbCopy.Image = global::Jonathan.InternalImages.CopyHS;
			this.tsbCopy.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbCopy.Name = "tsbCopy";
			this.tsbCopy.Size = new System.Drawing.Size(23, 22);
			this.tsbCopy.Text = "Copy";
			this.tsbCopy.Click += new System.EventHandler(this.tsbCopy_Click);
			// 
			// tsbPaste
			// 
			this.tsbPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbPaste.Image = global::Jonathan.InternalImages.PasteHS;
			this.tsbPaste.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbPaste.Name = "tsbPaste";
			this.tsbPaste.Size = new System.Drawing.Size(23, 22);
			this.tsbPaste.Text = "Paste";
			this.tsbPaste.Click += new System.EventHandler(this.tsbPaste_Click);
			// 
			// toolStripSeparator2
			// 
			this.toolStripSeparator2.Name = "toolStripSeparator2";
			this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
			// 
			// tsbBold
			// 
			this.tsbBold.CheckOnClick = true;
			this.tsbBold.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbBold.Image = global::Jonathan.InternalImages.boldhs;
			this.tsbBold.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbBold.Name = "tsbBold";
			this.tsbBold.Size = new System.Drawing.Size(23, 22);
			this.tsbBold.Text = "Bold";
			this.tsbBold.Click += new System.EventHandler(this.tsbBold_Click);
			// 
			// tsbItalic
			// 
			this.tsbItalic.CheckOnClick = true;
			this.tsbItalic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbItalic.Image = global::Jonathan.InternalImages.ItalicHS;
			this.tsbItalic.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbItalic.Name = "tsbItalic";
			this.tsbItalic.Size = new System.Drawing.Size(23, 22);
			this.tsbItalic.Text = "Italic";
			this.tsbItalic.Click += new System.EventHandler(this.tsbItalic_Click);
			// 
			// tsbUnderline
			// 
			this.tsbUnderline.CheckOnClick = true;
			this.tsbUnderline.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbUnderline.Image = global::Jonathan.InternalImages.Underline;
			this.tsbUnderline.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbUnderline.Name = "tsbUnderline";
			this.tsbUnderline.Size = new System.Drawing.Size(23, 22);
			this.tsbUnderline.Text = "Underline";
			this.tsbUnderline.Click += new System.EventHandler(this.tsbUnderline_Click);
			// 
			// tsbStrike
			// 
			this.tsbStrike.CheckOnClick = true;
			this.tsbStrike.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbStrike.Image = global::Jonathan.InternalImages.strikeout;
			this.tsbStrike.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbStrike.Name = "tsbStrike";
			this.tsbStrike.Size = new System.Drawing.Size(23, 22);
			this.tsbStrike.Text = "Strike Through";
			this.tsbStrike.Click += new System.EventHandler(this.tsbStrike_Click);
			// 
			// toolStripSeparator3
			// 
			this.toolStripSeparator3.Name = "toolStripSeparator3";
			this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25);
			// 
			// tsbLeft
			// 
			this.tsbLeft.CheckOnClick = true;
			this.tsbLeft.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbLeft.Image = global::Jonathan.InternalImages.left;
			this.tsbLeft.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbLeft.Name = "tsbLeft";
			this.tsbLeft.Size = new System.Drawing.Size(23, 22);
			this.tsbLeft.Text = "Left Alignment";
			this.tsbLeft.Click += new System.EventHandler(this.tsbLeft_Click);
			// 
			// tsbCenter
			// 
			this.tsbCenter.CheckOnClick = true;
			this.tsbCenter.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbCenter.Image = global::Jonathan.InternalImages.center;
			this.tsbCenter.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbCenter.Name = "tsbCenter";
			this.tsbCenter.Size = new System.Drawing.Size(23, 22);
			this.tsbCenter.Text = "Center Alignment";
			this.tsbCenter.Click += new System.EventHandler(this.tsbCenter_Click);
			// 
			// tsbRight
			// 
			this.tsbRight.CheckOnClick = true;
			this.tsbRight.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbRight.Image = global::Jonathan.InternalImages.right;
			this.tsbRight.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbRight.Name = "tsbRight";
			this.tsbRight.Size = new System.Drawing.Size(23, 22);
			this.tsbRight.Text = "Right Alignment";
			this.tsbRight.Click += new System.EventHandler(this.tsbRight_Click);
			// 
			// toolStripSeparator4
			// 
			this.toolStripSeparator4.Name = "toolStripSeparator4";
			this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25);
			// 
			// tsbUndo
			// 
			this.tsbUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbUndo.Image = global::Jonathan.InternalImages.Edit_UndoHS;
			this.tsbUndo.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbUndo.Name = "tsbUndo";
			this.tsbUndo.Size = new System.Drawing.Size(23, 22);
			this.tsbUndo.Text = "Undo";
			this.tsbUndo.Click += new System.EventHandler(this.tsbUndo_Click);
			// 
			// tsbRedo
			// 
			this.tsbRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbRedo.Image = global::Jonathan.InternalImages.Edit_RedoHS;
			this.tsbRedo.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbRedo.Name = "tsbRedo";
			this.tsbRedo.Size = new System.Drawing.Size(23, 22);
			this.tsbRedo.Text = "Redo";
			this.tsbRedo.Click += new System.EventHandler(this.tsbRedo_Click);
			// 
			// toolStripSeparator5
			// 
			this.toolStripSeparator5.Name = "toolStripSeparator5";
			this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25);
			// 
			// tsbFont
			// 
			this.tsbFont.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbFont.Image = global::Jonathan.InternalImages.FontDialogHS;
			this.tsbFont.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbFont.Name = "tsbFont";
			this.tsbFont.Size = new System.Drawing.Size(23, 22);
			this.tsbFont.Text = "Change Font";
			this.tsbFont.Click += new System.EventHandler(this.tsbFont_Click);
			// 
			// tsbColor
			// 
			this.tsbColor.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbColor.Image = global::Jonathan.InternalImages.Color_font;
			this.tsbColor.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbColor.Name = "tsbColor";
			this.tsbColor.Size = new System.Drawing.Size(23, 22);
			this.tsbColor.Text = "Color";
			this.tsbColor.Click += new System.EventHandler(this.tsbColor_Click);
			// 
			// tsbStamp
			// 
			this.tsbStamp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbStamp.Image = global::Jonathan.InternalImages.stamp;
			this.tsbStamp.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbStamp.Name = "tsbStamp";
			this.tsbStamp.Size = new System.Drawing.Size(23, 22);
			this.tsbStamp.Text = "Time Stamp";
			this.tsbStamp.Click += new System.EventHandler(this.tsbStamp_Click);
			// 
			// tsbPrint
			// 
			this.tsbPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
			this.tsbPrint.Image = global::Jonathan.InternalImages.PrintHS;
			this.tsbPrint.ImageTransparentColor = System.Drawing.Color.Magenta;
			this.tsbPrint.Name = "tsbPrint";
			this.tsbPrint.Size = new System.Drawing.Size(23, 22);
			this.tsbPrint.Text = "Print";
			this.tsbPrint.Click += new System.EventHandler(this.tsbPrint_Click);
			// 
			// openFileDialog
			// 
			this.openFileDialog.Title = "Open File...";
			// 
			// ctrlTextNote
			// 
			this.BackColor = System.Drawing.Color.White;
			this.Controls.Add(this.picSave);
			this.Controls.Add(this.rtbNotes);
			this.Controls.Add(this.toolStrip1);
			this.Name = "ctrlTextNote";
			this.Size = new System.Drawing.Size(856, 408);
			((System.ComponentModel.ISupportInitialize)(this.picSave)).EndInit();
			this.toolStrip1.ResumeLayout(false);
			this.toolStrip1.PerformLayout();
			this.ResumeLayout(false);
			this.PerformLayout();

		}
		#endregion

		#region Selection Change event	
		[Description("Occurs when the selection is changed"),
		Category("Behavior")]
			// Raised in tb1 SelectionChanged event so that user can do useful things
		public event System.EventHandler SelChanged;
		#endregion

		#region Stamp Event Stuff
		[Description("Occurs when the stamp button is clicked"), 
		Category("Behavior")]
		public event System.EventHandler Stamp;
        
		/// <summary>
		/// OnStamp event
		/// </summary>
		protected virtual void OnStamp(EventArgs e)
		{
			if(Stamp != null)
				Stamp(this, e);

			switch(StampAction)
			{
				case StampActions.EditedBy:
				{
					StringBuilder stamp = new StringBuilder(""); //holds our stamp text
					if(rtbNotes.Text.Length > 0) stamp.Append("\n\n\n\n"); //add two lines for space
					stamp.Append("Edited by "); 
					//use the CurrentPrincipal name if one exsist else use windows logon username
					if(Thread.CurrentPrincipal == null || Thread.CurrentPrincipal.Identity == null || Thread.CurrentPrincipal.Identity.Name.Length <= 0)
						stamp.Append(Environment.UserName);
					else
						stamp.Append(Thread.CurrentPrincipal.Identity.Name);
					stamp.Append(" on " + DateTime.Now.ToLongDateString() + "\n\n");
			
					rtbNotes.SelectionLength = 0; //unselect everything basicly
					rtbNotes.SelectionStart = rtbNotes.Text.Length; //start new selection at the end of the text
					rtbNotes.SelectionColor = this.StampColor; //make the selection blue
					rtbNotes.SelectionFont = new Font(rtbNotes.SelectionFont, FontStyle.Bold); //set the selection font and style
					rtbNotes.AppendText(stamp.ToString()); //add the stamp to the richtextbox
					rtbNotes.Focus(); //set focus back on the richtextbox
				} break; //end edited by stamp
				case StampActions.DateTime:
				{
					StringBuilder stamp = new StringBuilder(""); //holds our stamp text
					if(rtbNotes.Text.Length > 0) stamp.Append("\n\n\n\n"); //add two lines for space
					stamp.Append(DateTime.Now.ToLongDateString() + "\n\n");
					rtbNotes.SelectionLength = 0; //unselect everything basicly
					rtbNotes.SelectionStart = rtbNotes.Text.Length; //start new selection at the end of the text
					rtbNotes.SelectionColor = this.StampColor; //make the selection blue
					rtbNotes.SelectionFont = new Font(rtbNotes.SelectionFont, FontStyle.Bold); //set the selection font and style
					rtbNotes.AppendText(stamp.ToString()); //add the stamp to the richtextbox
					rtbNotes.Focus(); //set focus back on the richtextbox
				} break;
			} //end select
		}
		#endregion

		#region Update Toolbar
		/// <summary>
		///     Update the toolbar button statuses
		/// </summary>
		public void UpdateToolbar()
		{
			// Get the font, fontsize and style to apply to the toolbar buttons
			Font fnt = GetFontDetails();
			// Set font style buttons to the styles applying to the entire selection
			FontStyle style = fnt.Style;
			
			//Set all the style buttons using the gathered style
			tsbBold.Checked = fnt.Bold; //bold button
            tsbItalic.Checked = fnt.Italic; //italic button
            tsbUnderline.Checked = fnt.Underline; //underline button
            tsbStrike.Checked = fnt.Strikeout; //strikeout button
            tsbLeft.Checked = (rtbNotes.SelectionAlignment == HorizontalAlignment.Left); //justify left
            tsbCenter.Checked = (rtbNotes.SelectionAlignment == HorizontalAlignment.Center); //justify center
            tsbRight.Checked = (rtbNotes.SelectionAlignment == HorizontalAlignment.Right); //justify right
		}
		#endregion

		#region RichTextBox Selection Change
		/// <summary>
		///		Change the toolbar buttons when new text is selected
		///		and raise event SelChanged
		/// </summary>
		private void rtbNotes_SelectionChanged(object sender, System.EventArgs e)
		{
			//Update the toolbar buttons
			UpdateToolbar();
			
			//Send the SelChangedEvent
			if (SelChanged != null)
				SelChanged(this, e);
		}
		#endregion

		#region Color Click
		/// <summary>
		///     Change the richtextbox color
		/// </summary>
		private void Color_Click(object sender, System.EventArgs e)
		{
			//set the richtextbox color based on the name of the menu item
			ChangeFontColor(Color.FromName(((MenuItem)sender).Text));
		}
		#endregion

		#region Font Click
		/// <summary>
		///     Change the richtextbox font
		/// </summary>
		private void Font_Click(object sender, System.EventArgs e)
		{
			// Set the font for the entire selection
			ChangeFont(((MenuItem)sender).Text);
		}
		#endregion

		#region Font Size Click
		/// <summary>
		///     Change the richtextbox font size
		/// </summary>
		private void FontSize_Click(object sender, System.EventArgs e)
		{
			//set the richtextbox font size based on the name of the menu item
			ChangeFontSize(float.Parse(((MenuItem)sender).Text));
		}
		#endregion

		#region Link Clicked
		/// <summary>
		/// Starts the default browser if a link is clicked
		/// </summary>
		private void rtbNotes_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e)
		{
			System.Diagnostics.Process.Start(e.LinkText);
		}
		#endregion

		#region Public Properties
		/// <summary>
		///     Determines how the stamp button will respond
		/// </summary>
		StampActions m_StampAction = StampActions.EditedBy;
		[Description("Determines how the stamp button will respond"),
		Category("Behavior")]
		public StampActions StampAction
		{
			get { return m_StampAction; }
			set { m_StampAction = value; }
		}
		
		/// <summary>
		///     Color of the stamp text
		/// </summary>
		Color m_StampColor = Color.Blue;

		[Description("Color of the stamp text"),
		Category("Appearance")]
		public Color StampColor
		{
			get { return m_StampColor; }
			set { m_StampColor = value; }
		}
		#endregion

		#region Change font
		/// <summary>
		///     Change the richtextbox font for the current selection
		/// </summary>
		public void ChangeFont(string fontFamily)
		{
			//This method should handle cases that occur when multiple fonts/styles are selected
			// Parameters:-
			// fontFamily - the font to be applied, eg "Courier New"

			// Reason: The reason this method and the others exist is because
			// setting these items via the selection font doen't work because
			// a null selection font is returned for a selection with more 
			// than one font!
			
			int rtbNotesstart = rtbNotes.SelectionStart;				
			int len = rtbNotes.SelectionLength; 
			int rtbTempStart = 0;						

			// If len <= 1 and there is a selection font, amend and return
			if (len <= 1 && rtbNotes.SelectionFont != null)
			{
				rtbNotes.SelectionFont =
					new Font(fontFamily, rtbNotes.SelectionFont.Size, rtbNotes.SelectionFont.Style);
				return;
			}

			// Step through the selected text one char at a time
			rtbTemp.Rtf = rtbNotes.SelectedRtf;
			for(int i = 0; i < len; ++i) 
			{ 
				rtbTemp.Select(rtbTempStart + i, 1); 
				rtbTemp.SelectionFont = new Font(fontFamily, rtbTemp.SelectionFont.Size, rtbTemp.SelectionFont.Style);
			}

			// Replace & reselect
			rtbTemp.Select(rtbTempStart,len);
			rtbNotes.SelectedRtf = rtbTemp.SelectedRtf;
			rtbNotes.Select(rtbNotesstart,len);
			return;
		}
		#endregion

		#region Change font style
		/// <summary>
		///     Change the richtextbox style for the current selection
		/// </summary>
		public void ChangeFontStyle(FontStyle style, bool add)
		{
			//This method should handle cases that occur when multiple fonts/styles are selected
			// Parameters:-
			//	style - eg FontStyle.Bold
			//	add - IF true then add else remove
			
			// throw error if style isn't: bold, italic, strikeout or underline
			if (   style != FontStyle.Bold
				&& style != FontStyle.Italic
				&& style != FontStyle.Strikeout
				&& style != FontStyle.Underline)
				throw new  System.InvalidProgramException("Invalid style parameter to ChangeFontStyle");
			
			int rtbNotesstart = rtbNotes.SelectionStart;				
			int len = rtbNotes.SelectionLength; 
			int rtbTempStart = 0;			
			
			//if len <= 1 and there is a selection font then just handle and return
			if(len <= 1 && rtbNotes.SelectionFont != null)
			{
				//add or remove style 
				if (add)
					rtbNotes.SelectionFont = new Font(rtbNotes.SelectionFont, rtbNotes.SelectionFont.Style | style);
				else
					rtbNotes.SelectionFont = new Font(rtbNotes.SelectionFont, rtbNotes.SelectionFont.Style & ~style);
				
				return;
			}
			
			// Step through the selected text one char at a time	
			rtbTemp.Rtf = rtbNotes.SelectedRtf;
			for(int i = 0; i < len; ++i) 
			{ 
				rtbTemp.Select(rtbTempStart + i, 1); 

				//add or remove style 
				if (add)
					rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style | style);
				else
					rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style & ~style);
			}

			// Replace & reselect
			rtbTemp.Select(rtbTempStart,len);
			rtbNotes.SelectedRtf = rtbTemp.SelectedRtf;
			rtbNotes.Select(rtbNotesstart,len);
			return;
		}
		#endregion

		#region Change font size
		/// <summary>
		///     Change the richtextbox font size for the current selection
		/// </summary>
		public void ChangeFontSize(float fontSize)
		{
			//This method should handle cases that occur when multiple fonts/styles are selected
			// Parameters:-
			// fontSize - the fontsize to be applied, eg 33.5
			
			if (fontSize <= 0.0)
				throw new System.InvalidProgramException("Invalid font size parameter to ChangeFontSize");
			
			int rtbNotesstart = rtbNotes.SelectionStart;				
			int len = rtbNotes.SelectionLength; 
			int rtbTempStart = 0;

			// If len <= 1 and there is a selection font, amend and return
			if (len <= 1 && rtbNotes.SelectionFont != null)
			{
				rtbNotes.SelectionFont =
					new Font(rtbNotes.SelectionFont.FontFamily, fontSize, rtbNotes.SelectionFont.Style);
				return;
			}
			
			// Step through the selected text one char at a time
			rtbTemp.Rtf = rtbNotes.SelectedRtf;
			for(int i = 0; i < len; ++i) 
			{ 
				rtbTemp.Select(rtbTempStart + i, 1); 
				rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont.FontFamily, fontSize, rtbTemp.SelectionFont.Style);
			}

			// Replace & reselect
			rtbTemp.Select(rtbTempStart,len);
			rtbNotes.SelectedRtf = rtbTemp.SelectedRtf;
			rtbNotes.Select(rtbNotesstart,len);
			return;
		}
		#endregion

		#region Change font color
		/// <summary>
		///     Change the richtextbox font color for the current selection
		/// </summary>
		public void ChangeFontColor(Color newColor)
		{
			//This method should handle cases that occur when multiple fonts/styles are selected
			// Parameters:-
			//	newColor - eg Color.Red
			
			int rtbNotesstart = rtbNotes.SelectionStart;				
			int len = rtbNotes.SelectionLength; 
			int rtbTempStart = 0;			
			
			//if len <= 1 and there is a selection font then just handle and return
			if(len <= 1 && rtbNotes.SelectionFont != null)
			{
				rtbNotes.SelectionColor = newColor;
				return;
			}
			
			// Step through the selected text one char at a time	
			rtbTemp.Rtf = rtbNotes.SelectedRtf;
			for(int i = 0; i < len; ++i) 
			{ 
				rtbTemp.Select(rtbTempStart + i, 1); 

				//change color
				rtbTemp.SelectionColor = newColor;
			}

			// Replace & reselect
			rtbTemp.Select(rtbTempStart,len);
			rtbNotes.SelectedRtf = rtbTemp.SelectedRtf;
			rtbNotes.Select(rtbNotesstart,len);
			return;
		}
		#endregion

		#region Get Font Details
		/// <summary>
		///     Returns a Font with:
		///     1) The font applying to the entire selection, if none is the default font. 
		///     2) The font size applying to the entire selection, if none is the size of the default font.
		///     3) A style containing the attributes that are common to the entire selection, default regular.
		/// </summary>		
		/// 
		public Font GetFontDetails()
		{
			//This method should handle cases that occur when multiple fonts/styles are selected
			
			int rtbNotesstart = rtbNotes.SelectionStart;				
			int len = rtbNotes.SelectionLength; 
			int rtbTempStart = 0;

			if (len <= 1)						
			{
				// Return the selection or default font
				if (rtbNotes.SelectionFont != null)
					return rtbNotes.SelectionFont;
				else
					return rtbNotes.Font;
			}

			// Step through the selected text one char at a time	
			// after setting defaults from first char
			rtbTemp.Rtf = rtbNotes.SelectedRtf;
		
			//Turn everything on so we can turn it off one by one
			FontStyle replystyle =			
				FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline;
			
			// Set reply font, size and style to that of first char in selection.
			rtbTemp.Select(rtbTempStart, 1);
			string replyfont = rtbTemp.SelectionFont.Name;
			float replyfontsize = rtbTemp.SelectionFont.Size;
			replystyle = replystyle & rtbTemp.SelectionFont.Style;
			
			// Search the rest of the selection
			for(int i = 1; i < len; ++i)				
			{ 
				rtbTemp.Select(rtbTempStart + i, 1); 
				
				// Check reply for different style
				replystyle = replystyle & rtbTemp.SelectionFont.Style;
				
				// Check font
				if (replyfont != rtbTemp.SelectionFont.FontFamily.Name)
					replyfont = "";

				// Check font size
				if (replyfontsize != rtbTemp.SelectionFont.Size)
					replyfontsize = (float)0.0;
			}

			// Now set font and size if more than one font or font size was selected
			if (replyfont == "")
				replyfont = rtbTemp.Font.FontFamily.Name;

			if (replyfontsize == 0.0)
				replyfontsize = rtbTemp.Font.Size;

			// generate reply font
			Font reply 
				= new Font(replyfont, replyfontsize, replystyle);
			
			return reply;
		}
		#endregion

		#region Menu
		private void rtbNotes_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if(e.Button == MouseButtons.Right)
			{
                ContextMenuStrip popUp = new ContextMenuStrip();

				ToolStripMenuItem mnuCpy = new ToolStripMenuItem("Copy", global::Jonathan.InternalImages.CopyHS);
				ToolStripMenuItem mnuPst = new ToolStripMenuItem("Paste", global::Jonathan.InternalImages.PasteHS);
				ToolStripMenuItem mnuSave = new ToolStripMenuItem("Save", global::Jonathan.InternalImages.saveHS);

				mnuCpy.Click += new EventHandler(mnuCpy_Click);
				mnuPst.Click += new EventHandler(mnuPst_Click);
				mnuSave.Click += new EventHandler(mnuSave_Click);

				popUp.Items.AddRange(new ToolStripMenuItem[]{mnuCpy, mnuPst, mnuSave});
                popUp.Show(rtbNotes, e.X, e.Y);
			}
		}

		private void mnuCpy_Click(object sender, System.EventArgs e)
		{
			rtbNotes.Copy();
		}

		private void mnuPst_Click(object sender, System.EventArgs e)
		{
			rtbNotes.Paste();
		}

		private void mnuSave_Click(object sender, System.EventArgs e)
		{
            rtbNotes.SaveFile(this.m_FileName);
		}

		private void rtbNotes_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if(e.Control && e.KeyCode == Keys.B)
			{
				ChangeFontStyle(FontStyle.Bold, !tsbBold.Checked);
			}
			if(e.Control && e.KeyCode == Keys.I)
			{
                ChangeFontStyle(FontStyle.Italic, !tsbItalic.Checked);
			}
			if(e.Control && e.KeyCode == Keys.U)
			{
                ChangeFontStyle(FontStyle.Underline, !tsbUnderline.Checked);
			}
			if(e.Control && e.KeyCode == Keys.S)
			{
				this.Save();
			}
		}
		#endregion

		#region Save

		private void picSave_VisibleChanged(object sender, System.EventArgs e)
		{
			if(picSave.Visible)
            {
                Application.DoEvents();
                Thread.Sleep(500);
                this.picSave.Visible = false;
			}
		}

		/// <summary>
		/// Saves the current Text Note.
		/// </summary>
		private void Save ()
		{
			if (!string.IsNullOrEmpty(this.m_FileName))
			{
				this.picSave.Visible = true;
				this.rtbNotes.SaveFile(this.m_FileName);
			}
			else
			{
				if (this.sfd1.ShowDialog() == DialogResult.OK)
				{
					this.m_FileName = this.sfd1.FileName;
					this.rtbNotes.SaveFile(this.m_FileName);
					FileInfo f = new FileInfo(this.m_FileName);
					this.m_NoteTab.TabTitle = f.Name;
				}
			}
		}

		#endregion

		#region Printing

		private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
		{
			float linesPerPage = 0;
			float yPosition = 0;
			int count = 0;
			float leftMargin = ev.MarginBounds.Left;
			float topMargin = ev.MarginBounds.Top; 
			string line = null;
			Font printFont = this.rtbNotes.Font;
			SolidBrush myBrush = new SolidBrush(Color.Black);

			// Work out the number of lines per page, using the MarginBounds. 

			linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);

			// Iterate over the string using the StringReader, printing each line. 

			while(count < linesPerPage && ((line = myReader.ReadLine()) != null))
			{

				// calculate the next line position based on
				// the height of the font according to the printing device 

				yPosition = topMargin + (count * printFont.GetHeight(ev.Graphics));

				// draw the next line in the rich edit control 

				ev.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());

				count++;
			}

			// If there are more lines, print another page. 

			if  (line != null)
				ev.HasMorePages = true;
			else
				ev.HasMorePages = false;

			myBrush.Dispose();
		}
		#endregion

        #region Tool Bar
        private void tsbSave_Click(object sender, EventArgs e)
        {
			this.Save();
        }

        private void tsbCut_Click(object sender, EventArgs e)
        {
            if (rtbNotes.SelectedText.Length >= 0)
                rtbNotes.Cut();
        }

        private void tsbCopy_Click(object sender, EventArgs e)
        {
            if (rtbNotes.SelectedText.Length >= 0)
                rtbNotes.Copy();
        }

        private void tsbPaste_Click(object sender, EventArgs e)
        {
            try
            { rtbNotes.Paste(); }
            catch{}
        }

        private void tsbBold_Click(object sender, EventArgs e)
        {
            ChangeFontStyle(FontStyle.Bold, tsbBold.Checked);
        }

        private void tsbItalic_Click(object sender, EventArgs e)
        {
            ChangeFontStyle(FontStyle.Italic, tsbItalic.Checked);
        }

        private void tsbUnderline_Click(object sender, EventArgs e)
        {
            ChangeFontStyle(FontStyle.Underline, tsbUnderline.Checked);
        }

        private void tsbStrike_Click(object sender, EventArgs e)
        {
            ChangeFontStyle(FontStyle.Strikeout, tsbStrike.Checked);
        }

        private void tsbLeft_Click(object sender, EventArgs e)
        {
            //change horizontal alignment to left
            rtbNotes.SelectionAlignment = HorizontalAlignment.Left;
            tsbCenter.Checked = false;
            tsbRight.Checked = false;
        }

        private void tsbCenter_Click(object sender, EventArgs e)
        {
            //change horizontal alignment to center
            tsbLeft.Checked = false;
            rtbNotes.SelectionAlignment = HorizontalAlignment.Center;
            tsbRight.Checked = false;
        }

        private void tsbRight_Click(object sender, EventArgs e)
        {
            //change horizontal alignment to right
            tsbLeft.Checked = false;
            tsbCenter.Checked = false;
            rtbNotes.SelectionAlignment = HorizontalAlignment.Right;
        }

        private void tsbUndo_Click(object sender, EventArgs e)
        {
            rtbNotes.Undo();
        }

        private void tsbRedo_Click(object sender, EventArgs e)
        {
            rtbNotes.Redo();
        }

        private void tsbFont_Click(object sender, EventArgs e)
        {
            if (fontDialog.ShowDialog() == DialogResult.OK)
            {
                ChangeFont(fontDialog.Font.FontFamily.ToString());
                ChangeFontSize(fontDialog.Font.Size);
            }
        }

        private void tsbColor_Click(object sender, EventArgs e)
        {
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                ChangeFontColor(colorDialog.Color);
            }
        }

        private void tsbStamp_Click(object sender, EventArgs e)
        {
            OnStamp(new EventArgs()); //send stamp event
        }

        private void tsbPrint_Click(object sender, EventArgs e)
        {
            printDialog1.Document = printDocument1;
            string strText = this.rtbNotes.Text;
            myReader = new StringReader(strText);
            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                this.printDocument1.Print();
            }
        }
        #endregion

		#region - Setup -

		/// <summary>
		/// Sets the Note's Tabber page...
		/// </summary>
		/// <param name="noteTab">Note's TabberPage.</param>
		public void SetNoteTab (ctrlNote noteTab)
		{
			this.m_NoteTab = noteTab;
			this.rtbNotes.Focus();
		}

		/// <summary>
		/// Gets the File associated with the note...
		/// </summary>
		public string File
		{
			get { return this.m_FileName; }
		}

		/// <summary>
		/// Opens the given file...
		/// </summary>
		/// <param name="filePath">Path of File to Open.</param>
		public void OpenFile (string filePath)
		{
			FileInfo fi = new FileInfo(filePath);
			this.openFileDialog.InitialDirectory = fi.Directory.FullName;
			StringBuilder sb = new StringBuilder();
			this.m_NoteTab.TabTitle = fi.Name;
			this.m_NoteTab.ToolTip = fi.FullName;
			this.m_FileName = fi.FullName;
			this.rtbNotes.LoadFile(filePath);
		}

		#endregion
	}
}
